package baize

import (
	"baize/app/utils/stringUtils"
	"github.com/baizeplus/sqly"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type BaseEntity struct {
	CreateBy   int64  `json:"createBy" bson:"create_by"`                            //创建人Id
	CreateName string `json:"createName" bson:"create_name"`                        //创建人Name
	CreateTime *Time  `json:"createTime" bson:"create_time"  swaggertype:"integer"` //创建时间
	UpdateBy   int64  `json:"updateBy" bson:"update_by"`                            //修改人Id
	UpdateName string `json:"updateName" bson:"update_name"`                        //修改人Name
	UpdateTime *Time  `json:"updateTime" db:"update_time"  swaggertype:"integer"`   //修改时间
}

func (b *BaseEntity) SetCreateBy(userId int64, userName string) {
	b.CreateBy = userId
	b.CreateName = userName
	kt := NewTime()
	b.CreateTime = kt
	b.UpdateBy = userId
	b.UpdateName = userName
	b.UpdateTime = kt
}

//func (b *BaseEntity) SetCreateByContext(c *gin.Context) {
//	b.UpdateBy, b.UpdateName = baizeContext.GetUserIdAndName(c)
//	kt := NewTime()
//	b.CreateTime = kt
//	b.UpdateBy = b.UpdateBy
//	b.UpdateName = b.UpdateName
//	b.UpdateTime = kt
//}

func (b *BaseEntity) SetUpdateBy(userId int64, userName string) {
	b.UpdateBy = userId
	b.UpdateTime = NewTime()
	b.UpdateName = userName
}

//func (b *BaseEntity) SetUpdateByContext(c *gin.Context) {
//	b.UpdateBy, b.UpdateName = baizeContext.GetUserIdAndName(c)
//	b.UpdateTime = NewTime()
//
//}

type BaseEntityDQL struct {
	DataScope []int64 `swaggerignore:"true"`
	OrderBy   string  `form:"orderBy" `              //排序字段
	IsAsc     string  `form:"isAsc" `                //排序规则  降序desc   asc升序
	Page      int64   `form:"pageNum" default:"1"`   //第几页
	Size      int64   `form:"pageSize" default:"10"` //数量
}

func (b *BaseEntityDQL) GetOrder() string {
	if b.OrderBy != "" {
		return " " + stringUtils.ToUnderScoreCase(b.OrderBy) + " " + b.IsAsc
	}
	return ""
}
func (b *BaseEntityDQL) ToPage() *sqly.Page {
	s := new(sqly.Page)
	s.Page = b.Page
	s.Size = b.Size
	s.OrderBy = b.GetOrder()
	return s
}
func (b *BaseEntityDQL) GetSize() int64 {
	if b.Size < 1 {
		b.Size = 10
	}
	if b.Size > 10000 {
		b.Size = 10000
	}
	return b.Size
}
func (b *BaseEntityDQL) GetPage() int64 {
	if b.Page < 1 {
		b.Page = 1
	}
	return b.Page
}
func (b *BaseEntityDQL) GetOffset() int64 {
	return (b.GetPage() - 1) * b.GetSize()
}
func (b *BaseEntityDQL) GetMongoLimit() *options.FindOptions {
	fo := new(options.FindOptions)
	fo.SetSkip(b.GetOffset())
	fo.SetLimit(b.GetSize())
	return fo
}
